package com.sinoglobal.ningxia.activity.mico;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.adapter.NewVideoPagerAdapter;
import com.sinoglobal.ningxia.beans.PageTitleImageBean;
import com.sinoglobal.ningxia.beans.ProgramaListBean;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.fragment.NewVideoFragment;
import com.sinoglobal.ningxia.fragment.RecommendLanMuFragment;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zhy.http.okhttp.request.RequestCall;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;


/**
 * Created by XINDZ on 2017/2/13.
 * 功能: 改版后的视频activity主要展示栏目
 */

public class NewMicroAudioVisualActivity extends BaseActivity implements View.OnClickListener {

    private MagicIndicator mcVideohome;
    private ViewPager vpVideoHome;

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String> mDataList = new ArrayList<>();
    private List<PageTitleImageBean> mLogoList = new ArrayList<>();
    private NewVideoPagerAdapter pagerAdapter;
    private CommonNavigatorAdapter commonNavigatorAdapter;
    private RelativeLayout programCard;
    private String cputype;
    private String FLAG = "flag";// 1代表解码播放，2代表webView播放
    private int NDK = 1;// 解码播放
    private int WEB = 2;// webView播放

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newmicroaudiovisual);
        openChenJInShi();
        titleView.setText("视频");
        templateButtonRight.setBackgroundResource(R.drawable.broadcast_icon);
        cputype = android.os.Build.CPU_ABI;
        //找到导航
        mcVideohome = (MagicIndicator) findViewById(R.id.mc_videohome);
        programCard = (RelativeLayout) findViewById(R.id.Rela_menu);
        programCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent go = new Intent();
                go.setClass(mActivity, PlayBillActivity.class);
                FlyUtil.intentForwardNetWork(mActivity, go);
            }
        });
        vpVideoHome = (ViewPager) findViewById(R.id.vp_videohome);
        vpVideoHome.setOffscreenPageLimit(5);

        pagerAdapter = new NewVideoPagerAdapter(getSupportFragmentManager());


        ResultCallback resultCallback = new ResultCallback(this) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                ProgramaListBean programaListBean = JSONObject.parseObject(response, ProgramaListBean.class);
                if (programaListBean != null && programaListBean.getCode() == 0) {
                    List<ProgramaListBean.ListBean> beanList = programaListBean.getList();
                    for (ProgramaListBean.ListBean listBean : beanList) {
                        String program = listBean.getProgram();
                        String classid = listBean.getClassid();
                        String img_url = listBean.getImg_url();
                        mDataList.add(program);
                        PageTitleImageBean pageTitleImageBean = new PageTitleImageBean(classid, img_url);
                        mLogoList.add(pageTitleImageBean);

                        if (classid.equals("0")) {
                            RecommendLanMuFragment recommendLanMuFragment = RecommendLanMuFragment.newInstance(listBean);
                            fragmentList.add(recommendLanMuFragment);
                        } else {

                            NewVideoFragment newVideoFragment = NewVideoFragment.newInstance(listBean);
                            fragmentList.add(newVideoFragment);
                        }
                    }
                    pagerAdapter.setFragmentList(fragmentList, mDataList);
                    vpVideoHome.setAdapter(pagerAdapter);
                    if (commonNavigatorAdapter != null) {
                        commonNavigatorAdapter.notifyDataSetChanged();
                    }
                }

            }
        };
        RequestCall requestCall = RemoteImpl.getInstance().getViedoList(this);
        requestCall.execute(resultCallback);

        pagerAdapter.setFragmentList(fragmentList, mDataList);
        vpVideoHome.setAdapter(pagerAdapter);
        vpVideoHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                JCVideoPlayer.releaseAllVideos();//viewpager滑动结束后关闭视频播放
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mcVideohome.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setScrollPivotX(0.5f);
        commonNavigatorAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(NewMicroAudioVisualActivity.this);
                View customLayout = LayoutInflater.from(NewMicroAudioVisualActivity.this).inflate(R.layout.title_pager_newvideo, null);
                final TextView tv_pager_title = (TextView) customLayout.findViewById(R.id.tv_pager_title);
                final ImageView iv_pager_title = (ImageView) customLayout.findViewById(R.id.iv_pager_title);
                tv_pager_title.setText(mDataList.get(index));
                setTitleDrawable(index, iv_pager_title, tv_pager_title);


                commonPagerTitleView.setContentView(customLayout);
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int index, int totalCount) {
                        tv_pager_title.setTextColor(getResources().getColor(R.color.red500));
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        tv_pager_title.setTextColor(getResources().getColor(R.color.black));
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {

                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {

                    }
                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        vpVideoHome.setCurrentItem(index);
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(1.6f));
                indicator.setLineHeight(UIUtil.dip2px(context, 1));
                indicator.setColors(getResources().getColor(R.color.red600));
                return indicator;
            }
        };
        commonNavigator.setAdapter(commonNavigatorAdapter);
        mcVideohome.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mcVideohome, vpVideoHome);
        toFM();

    }

    @SuppressLint("DefaultLocale")
    private void toFM() {
        templateButtonRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AndPermission.hasPermission(NewMicroAudioVisualActivity.this, Manifest.permission.WRITE_SETTINGS)) {
                    //有权限
                    goBroadCastActivity();
                } else {
                    AndPermission.with(NewMicroAudioVisualActivity.this)
                            .permission(Manifest.permission.WRITE_SETTINGS)
                            .requestCode(1004)
                            .send();
                }
            }
        });
    }

    /**
     * 设置pagertitle的图标
     *
     * @param index
     */
    private void setTitleDrawable(int index, final ImageView iv_pager_title, final TextView tv_pager_title) {
        PageTitleImageBean pageTitleImageBean = mLogoList.get(index);
        String titleClassId = pageTitleImageBean.getID();
        String titleLogo = pageTitleImageBean.getImageUrl();
        if (titleLogo != null && !titleLogo.equals("")) {
            Picasso.with(NewMicroAudioVisualActivity.this)
                    .load(ConnectionUtil.localUrl + titleLogo)
                    .placeholder(R.drawable.titlelogo50)
                    .error(R.drawable.titlelogo50)
                    .into(iv_pager_title);
        } else {
            if (titleClassId != null && !titleClassId.equals("0")) {
                iv_pager_title.setImageDrawable(getResources().getDrawable(R.drawable.titlelogo50));
            } else {
                iv_pager_title.setImageDrawable(null);
                iv_pager_title.setVisibility(View.GONE);
                tv_pager_title.setPadding(30, 0, 30, 0);
            }
        }
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1004)
    private void getLocationYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        goBroadCastActivity();
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1004)
    private void getLocationNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1004).show();
        }
    }

    /**
     * 前往广播页
     */
    private void goBroadCastActivity() {
        Intent goBroad = new Intent();
        goBroad.setClass(mActivity, BroadCastActivity.class);
        if (cputype == null)
            return;
        if (cputype.toLowerCase().contains("arm")) {
            goBroad.putExtra(FLAG, NDK);
            FlyUtil.intentForwardNetWork(mActivity, goBroad);
        }
        // 3.0之前的系统版本可以直接播放flash
        else if (checkSysVer()) {
            goBroad.putExtra(FLAG, WEB);
            FlyUtil.intentForwardNetWork(mActivity, goBroad);
        }
        // 手机本身有flash插件的也可以播放
        else if (checkFlash()) {
            goBroad.putExtra(FLAG, WEB);
            FlyUtil.intentForwardNetWork(mActivity, goBroad);
        }
        // 否则提示用户无法播放
        else {
            showShortToastMessage(getResources().getString(
                    R.string.nonSupportRadio));
        }
    }

    // 检查系统版本，2.x版本可以直接播放flash，
    private boolean checkSysVer() {
        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 10)
            return true;
        else
            return false;
    }

    // 检查是否有flash插件
    private boolean checkFlash() {
        PackageManager pm = getPackageManager();
        List<PackageInfo> infoList = pm
                .getInstalledPackages(PackageManager.GET_SERVICES);
        for (PackageInfo info : infoList) {
            if ("com.adobe.flashplayer".equals(info.packageName)) {
                return true;
            }
        }
        return false;
    }
}
